package org.tarena.dang.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.tarena.dang.entity.User;
import org.tarena.dang.util.DbUtil;

public class JdbcUserDAO implements UserDAO{
	private static final String save = "insert into d_user(" +
			"email,nickname,password,user_integral," +
			"is_email_verify,email_verify_code," +
			"last_login_time,last_login_ip) " +
			"values (?,?,?,?,?,?,?,?)";
	private static final String findByEmail = 
			"select * from d_user where email=?";
	
	private static final String changeVerify = "update d_user set is_email_verify=? where email=?";
	
	public void save(User user) throws Exception {
		Connection conn = DbUtil.getConnection();
		PreparedStatement pst = 
					conn.prepareStatement(save);
		pst.setString(1, user.getEmail());
		pst.setString(2, user.getNickname());
		pst.setString(3, user.getPassword());
		pst.setInt(4, user.getUserIntegral());
		pst.setString(5, user.getEmailVerify());
		pst.setString(6, user.getEmailVerifyCode());
		pst.setLong(7, user.getLastLoginTime());
		pst.setString(8, user.getLastLoginIp());
		pst.executeUpdate();
		DbUtil.closeConnection();
	}

	public User findByEmail(String email) throws Exception {
		Connection conn = DbUtil.getConnection();
		PreparedStatement pst = 
				conn.prepareStatement(findByEmail);
		pst.setString(1, email);
		ResultSet rs = pst.executeQuery();
		User user = null;
		if(rs.next()){
			user = new User();
			user.setId(rs.getInt("id"));
			user.setNickname(rs.getString("nickname"));
			user.setEmail(rs.getString("email"));
			user.setPassword(rs.getString("password"));
			user.setEmailVerify(rs.getString("is_email_verify"));
			user.setEmailVerifyCode(rs.getString("email_verify_code"));
			user.setUserIntegral(rs.getInt("user_integral"));
			user.setLastLoginTime(rs.getLong("last_login_time"));
			user.setLastLoginIp(rs.getString("last_login_ip"));
		}
		DbUtil.closeConnection();
		return user;
	}
	public void changeVerify(String email) throws Exception{
		Connection conn = DbUtil.getConnection();
		PreparedStatement pst = 
				conn.prepareStatement(changeVerify);
		pst.setString(1,"Y");
		pst.setString(2, email);
		pst.executeUpdate();
		DbUtil.closeConnection();
	}
}
